package com.finger.gulimall.ware.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.common.constant.WareConstant;
import com.finger.common.utils.PageUtils;
import com.finger.common.utils.Query;
import com.finger.gulimall.ware.dao.PurchaseDao;
import com.finger.gulimall.ware.entity.PurchaseDetailEntity;
import com.finger.gulimall.ware.entity.PurchaseEntity;
import com.finger.gulimall.ware.exception.WareException;
import com.finger.gulimall.ware.service.PurchaseDetailService;
import com.finger.gulimall.ware.service.PurchaseService;
import com.finger.gulimall.ware.service.WareSkuService;
import com.finger.gulimall.ware.entity.to.Item;
import com.finger.gulimall.ware.entity.vo.DoneVO;
import com.finger.gulimall.ware.entity.vo.MargeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /*
            page: 1
            limit: 10
            key:
            status:
         */
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> {
                w.like("assignee_name", key).or().eq("ware_id", key);
            });
        }

        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", status);
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void margePurchase(MargeVO margeVO) {
        Long finalPurchaseId = margeVO.getPurchaseId();
        List<Long> items = margeVO.getItems();
        // 如果采购单id为空，说明要新建采购单
        if (finalPurchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setPriority(0);
            purchaseEntity.setStatus(WareConstant.PurchaseEnume.ASSIGNED.getCode());
            this.save(purchaseEntity);
            finalPurchaseId = purchaseEntity.getId();
        }/*else{
            // 如果状态不为新建或已分配，则返回
            PurchaseEntity purchaseEntity = baseMapper.selectById(finalPurchaseId);
            if(!(purchaseEntity.getStatus() == WareConstant.PurchaseEnume.CREATED.getCode())||
                    !(purchaseEntity.getStatus() == WareConstant.PurchaseEnume.ASSIGNED.getCode())){
                throw new WareException("该采购单已被领取或已完成");
            }
        }*/
        List<Long> itemIds = margeVO.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.listByIds(itemIds);

        // 过滤掉猜采购需求不为 0 的数据，也就是订单状态不为新建的过滤掉
        List<PurchaseDetailEntity> detailEntityList = purchaseDetailEntityList.stream().filter(item -> {
//            if (item.getStatus() == WareConstant.PurchaseDetailEnume.CREATED.getCode()) {
//                return true;
//            }
            return item.getStatus() == WareConstant.PurchaseDetailEnume.CREATED.getCode();
        }).collect(Collectors.toList());

        if (detailEntityList.size() == 0 || detailEntityList == null) {
            throw new WareException("没有需要合并的采购需求", 10000);
        }
        Long finalPurchaseId1 = finalPurchaseId;
        detailEntityList.stream().forEach(item -> {
            item.setStatus(WareConstant.PurchaseDetailEnume.ASSIGNED.getCode());
            item.setPurchaseId(finalPurchaseId1);
        });
//        // 循环过滤得到要合并的采购需求
//        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(id -> {
//            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
//            detailEntity.setId(id);
//            detailEntity.setStatus(WareConstant.PurchaseDetailEnume.ASSIGNED.getCode());
//            detailEntity.setPurchaseId(finalPurchaseId1);
//            return detailEntity;
//        }).collect(Collectors.toList());

        // 批量更新采购需求状态
        purchaseDetailService.updateBatchById(detailEntityList);

        // 更新采购单修改时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        baseMapper.updateById(purchaseEntity);
    }

    @Transactional
    @Override
    public void done(DoneVO doneVo) {

        Long id = doneVo.getId();
        List<Item> items = doneVo.getItems();
        boolean flag = Boolean.TRUE;
        for (Item item : items) {
            // 这是已经采购成功的
            if (item.getStatus() == WareConstant.PurchaseDetailEnume.FINISH.getCode()) {
                Long purchaseDatailId = item.getItemId();
                PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(purchaseDatailId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnume.FINISH.getCode());
                purchaseDetailService.updateById(purchaseDetailEntity);
                wareSkuService.addStock(purchaseDetailEntity.getWareId(), purchaseDetailEntity.getSkuId(), purchaseDetailEntity.getSkuNum());

            } else {
                flag = Boolean.FALSE;
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getItemId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnume.BYINGERROR.getCode());
                purchaseDetailService.updateById(purchaseDetailEntity);
            }
        }

        if (!flag) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(id);
            purchaseEntity.setStatus(WareConstant.PurchaseEnume.HASERROR.getCode());
            baseMapper.updateById(purchaseEntity);
        } else {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(id);
            purchaseEntity.setStatus(WareConstant.PurchaseEnume.FINISH.getCode());
            baseMapper.updateById(purchaseEntity);
        }

    }

    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {

        // 遍历传过来的id集合
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = baseMapper.selectById(id);

            return purchaseEntity;
            // 过滤，过滤出状态为 新建（0） 或 已分配（1）
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseEnume.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseEnume.ASSIGNED.getCode()) {
                item.setStatus(WareConstant.PurchaseEnume.RECEIVE.getCode());
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        // 批量修改需要领取采购单的id
        this.updateBatchById(purchaseEntities);

        // 遍历要领取采购单集合，并修改该采购单下的每个采购需求的状态
        purchaseEntities.forEach(purchase -> {
            Long purchaseId = purchase.getId();
            List<PurchaseDetailEntity> list = purchaseDetailService.getPurchaseDetail(purchaseId);
            list.stream().forEach(item -> {
                item.setStatus(WareConstant.PurchaseDetailEnume.BYING.getCode());
            });
            purchaseDetailService.updateBatchById(list);
        });

    }

    @Override
    public PageUtils unreceiveList() {
        // 构建条件
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        // 设置条件
        queryWrapper.eq("status", 1);

        HashMap<String, Object> map = new HashMap<>();

        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(map), queryWrapper);

        return new PageUtils(page);
    }

}